<template>
	<view class="create-dish">
		<!-- 分类 -->
		<view class="row">
			<view class="row-label">分类：</view>
			<uni-data-select class="row-selector" v-model="dishTypeId" :clear="false" :localdata="range"
				:disabled="dishTypeDisable" @change="change"></uni-data-select>
		</view>
		<!-- 菜名 -->
		<view class="row">
			<view class="row-label">菜名：</view>
			<uni-easyinput class="dish-name" v-model="name" focus placeholder="菜名" />
		</view>
		<!-- 简介 -->
		<view class="row align-start">
			<view class="row-label">简介：</view>
			<uni-easyinput class="dish-create-card-dish-desc" v-model="description" type="textarea"
				placeholder="简介"></uni-easyinput>
		</view>
		<!-- 图片 -->
		<view class="row align-start">
			<view class="row-label" style="text-wrap: nowrap">
				图片：
			</view>
			<view class="image-uploader" @click="uploadImage">
				<image class="upload-icon" :src="imageUrl|| '../../static/icons/image.svg'" mode="aspectFill"></image>
				<!-- <view class="upload-tip">点击选择图片</view> -->
			</view>
		</view>
		<!-- 提交 -->
		<view class="submit-row">
			<button class="margin-0" type="default" plain @click="navigateBack">
				取消
			</button>
			<button class="margin-0" type="primary" @tap="onSubmit">
				确定
			</button>
		</view>
	</view>
</template>

<script>
	import {
		UploadUrl,
		BaseUrl
	} from "@/apis/config.js"
	import {
		getDishTypes
	} from '../../apis/dishType';
	import {
		createDish,
		updateDish,
		getDishByDishId
	} from '../../apis/dish.js';

	export default {
		data() {
			return {
				dishTypeDisable: false,
				range: [],
				id: '', // 菜品id
				dishTypeId: '', // 菜品分类id
				name: '',
				description: '',
				imageUrl: '',
			};
		},
		computed: {
			// dishTypeDisable() {
			// 	return !!this.dishTypeId;
			// },
		},
		created() {
			getDishTypes().then((res) => {
				// console.log('getDishTypes', res.data);
				this.range = res.data.map((type) => ({
					value: type.id,
					text: type.name,
				}));
			});
		},
		onLoad(e) {
			// dishType || dishId
			// console.log('onLoad', e);
			const dishId = parseInt(e.dishId);
			const dishTypeId = parseInt(e.dishTypeId);
			// 是否有菜品id
			if (dishId) {
				// 设置菜品信息
				this.setDishInfoByDishId(dishId);
			}
			// 是否有菜品分类id
			else if (e.dishTypeId) {
				this.dishTypeId = dishTypeId;
				// this.dishTypeDisable = true;
			}
		},
		methods: {
			validateForm() {
				let title = '';
				if (this.dishTypeId <= 0) {
					title = '没有选择分类';
				} else if (this.name <= 0) {
					title = '没有菜名';
				} else if (this.imageUrl <= 0) {
					// title = "没有选择分类"
				}

				if (title) {
					uni.showToast({
						title,
						icon: 'error',
					});

					return false;
				}
				return true;
			},
			onSubmit() {
				// console.log('on submit');
				if (this.id) {
					this.updateDishById();
				} else {
					this.createDish();
				}
			},
			// 修改菜品
			updateDishById() {
				uni.showLoading({
					title: '修改菜品',
				});

				updateDish({
						id: this.id,
						name: this.name,
						dishTypeId: this.dishTypeId,
						description: this.description,
						imageUrl: this.imageUrl,
					})
					.then((res) => {
						uni.navigateBack();
					})
					.catch((err) => {
						uni.hideLoading();
						uni.showToast({
							title: '出错了',
							icon: err.message,
						});
					})
					.finally(() => {
						uni.hideLoading();
					});
			},
			// 创建菜品
			createDish() {
				if (!this.validateForm()) return;
				uni.showLoading({
					title: '创建菜品',
				});
				createDish({
						dishTypeId: this.dishTypeId,
						name: this.name,
						description: this.description,
						imageUrl: this.imageUrl,
					})
					.then((res) => {
						this.navigateBack();
					})
					.finally(() => {
						uni.hideLoading();
					});
			},

			setDishInfoByDishId(id) {
				uni.showToast({
					icon: 'loading',
				});
				getDishByDishId(id)
					.then((res) => {
						// console.log('dish ', res);
						const dish = res.data;
						this.id = dish.id;
						this.dishTypeId = dish.dishTypeId;
						this.name = dish.name;
						this.description = dish.description;
						this.imageUrl = dish.imageUrl;
					})
					.finally(() => {
						uni.hideToast();
					});
			},
			uploadImage() {
				console.log('upload image');
				const that = this;
				// 调用uni-app的chooseImage API选择图片
				uni.chooseImage({
					count: 1, // 默认9，设置为1表示只能选择一张图片
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认都有
					success: (res) => {
						// console.log('chooseImage success', res);
						const url = BaseUrl + '/image-upload'
						const filePath = res.tempFilePaths[0]
						const name = "image"
						// 调用uni-app的uploadFile API上传图片
						uni.uploadFile({
							url, // Straapi的上传接口地址
							filePath, // 上传图片的路径
							name, // 后端用来解析文件流的字段名
							formData: {
								image: filePath,
								// token: 'your-token', // 如果需要的话，可以在这里添加额外的表单数据，比如token
							},
							success: (uploadRes) => {
								console.log('uploadFile success', uploadRes);
								if (uploadRes.statusCode === 200) {
									// 上传成功的处理
									const data = JSON.parse(uploadRes.data);
									console.log("upload success data", data);
									// 这里可以根据Strapi返回的数据进行进一步处理，比如获取图片URL
									that.imageUrl = UploadUrl + "/" + data.data.medium;
									// console.log("that.imageUrl", that.imageUrl);
								}
							},
							fail: (error) => {
								console.error('uploadFile fail', error);
								// 上传失败的处理
							},
						});
					},
					fail: (error) => {
						console.error('chooseImage fail', error);
						// 选择图片失败的处理
					},
				});
			},
			change(e) {
				console.log('e:', e);
			},
			navigateBack() {
				uni.navigateBack();
			},
		},
	};
</script>

<style scoped>
	.create-dish {
		padding: 26rpx;
	}

	.row {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.row-selector {
		width: 598rpx;
	}

	.row-label {
		width: 100rpx;
		text-wrap: nowrap;
	}

	.align-start {
		align-items: start;
	}

	.submit-row {
		margin-top: 86rpx;
		display: flex;
		align-items: center;
		justify-content: right;
		gap: 64rpx;
	}

	.image-uploader {
		/* position: relative; */
		/* background-color: #a1a0a5; */
	}

	.image-uploader .upload-icon {
		/* position: absolute; */
		width: 598rpx;
		height: 331rpx;
	}

	.margin-0 {
		margin: 0;
		flex: 1;
	}
</style>